<template>
<div>
  <headerSearch title="好友" :noBack ="true"></headerSearch>

  <div class="content">
    <div class="business_lists" v-for="friend in friendList"  @click="handleChat(friend.id)">
      <div class="business_left"><img :src="friend.avatar" alt=""></div> 
      <div class="business_desc"><h5>{{friend.username}}</h5> <p>耐思智慧得到餐饮耐思智慧饮耐思智有限公司</p></div>
    </div>
  </div>

	  	<so-footer></so-footer>
</div>
  
</template>

<script>
import headerSearch from '../public/header-search.vue';
import soFooter from '../components/footer-bar';
import {ws,friendList,imageUrl,updateChat,createChat} from '../api/api'
  export default {
    data() {
      return {
        search: '',
        friendList: [], // 好友列表
        haveNotReadApply: true,
        chatList: [],  // 聊天列表
      }
    },
    components: {
      // soHeader,
      headerSearch,
      soFooter,
      // headerSearch
      // headerText
    },
    computed: {
      imageUrl () {
        return imageUrl
      },
      // 获取头像
      avatar () {
        return this.$store.state.info.avatar
      },
      // 聊天搜索,排序
      filterChatList () {
        this.chatList = this.chatList.sort((a, b) => {
          if (a.online > b.online) {
            return -1
          } else if (a.online === b.online) {
            if (a.last_chat_time > b.last_chat_time) {
              return -1
            } else {
              return 1
            }
          } else {
            return 1
          }
        })
        if (this.search.chat !== '') {
          return this.chatList.filter((element) => {
            if (element.username) {
              return element.username.indexOf(this.search.chat) !== -1
            } else {
              return element.group_name.indexOf(this.search.chat) !== -1
            }
          })
        }
        console.log(9898);
        return this.chatList
      },
      filterFriendList () {
        if (this.search.friend !== '') {
          return this.friendList.filter((element) => {
            return element.username.indexOf(this.search.friend) !== -1
          })
        }
        return this.friendList
      }
    },
    methods : {
      // 开启ws链接
      openConnect () {
        let token = window.localStorage.getItem('access_token')

        this.socket = new WebSocket(`${ws}?token=${token}`)
        // this.onMessage
        this.socket.onopen = this.onConnect
        this.socket.onmessage = this.onMessage
        this.socket.onclose = this.onClose
        this.socket.onerror = this.onError
      },
      onError () {
        this.$confirm('聊天服务器连接失败', '提示', {
          confirmButtonText: '重新连接',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.openConnect()
        }).catch(() => {
          localStorage.setItem('token', '')
          this.$router.push('/')
        })
      },
      // 链接成功事件
      onConnect (ws) {
        this.$message.success(`已成功连接到聊天服务器`)
        this.isConnect = true
      },
      // 断开连接触发函数
      onClose () {
        this.isConnect = false
      },
      // 接受消息事件
      onMessage (ws) {
        // JSON.stringify(ws.data);
        // console.log('ws', 9595);return false;
        // let data = JSON.parse(ws.data);

        try {
            let data = JSON.parse(ws.data);
             switch (data.type) {
          case 'chatList': // 聊天列表
            this.chatList = data.chatList
            break
          case 'msg':
            this.handleMsg(data)
            break
          case 'forbidden':  // token不正确
            this.handleLoginOut()
            break
          case 'repeat':  // 被踢
            this.visible.reConnect = false
            this.socket.close()
            localStorage.setItem('token', '')
            this.$alert('你的账号已在别处登陆', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$router.push('/')
              }
            })
            break
          case 'newApply':   // 有新的好友申请
            this.haveNotReadApply = true
            break
          case 'applySucc':  // 好友申请被同意
            this.handleFriendList()
            this.$message.success('"' + data.friend.username + '"已经同意你的好友申请')
            break
          case 'newGroup': // 接受新群组
            this.chatList.unshift(data.group)
            break
          case 'repeatConnect': // 重复连接
            this.socket.close()
            this.visible.repeatConnect = true
            this.visible.reConnect = false
            break
          case 'goOnline':  // 上线消息
            let chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = true
            break
          case 'goOffLine':  // 下线消息
            chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = false
            break
          case 'quitGroup':   // 退出群组消息
            const chatId = data.chatId
            const userId = data.userId
            chat = this.chatList.find((element) => parseInt(element.chat_id) === parseInt(chatId))
            const index = chat.userList.findIndex(element => parseInt(element.id) === parseInt(userId))
            const user = chat.userList.splice(index, 1)
            this.$message.success(`<${user.username}>退出了群组<${chat.group_name}>`)
            break
        }
        } catch (err) {
            console.log(JSON.stringify(err));
        }

       
      },
      // 获取朋友列表
      handleFriendList () { 
        let access_token = window.localStorage.getItem('access_token');
        friendList({access_token: access_token}).then(res => {
          if(res.code == 200) {
            this.friendList = res.data;
          }
          // if (this.currentFriend.id === '' && this.friendList.length > 0) {
          //   this.selectFriend(this.friendList[0])
          // }
        })
      },
      // 点击朋友聊天事件
      handleChat (friendId) {
        let chat = this.chatList.find(e => parseInt(e.id) === parseInt(friendId))
        if (chat) {
          // 切换聊天对象
          this.$router.push({
            path: '/chat',
            query: {
              chat: chat
            }
          });
          // this.switchInterface('chat')  // 切换到聊天界面
          // this.changeChat(chat)    // 将当前聊天对象切换成该聊天
        } else {
          createChat({targetId: friendId}).then(res => {
            if (parseInt(res.status) === 1) {
              chat = res.chat
              // 切换聊天对象
              this.$router.push({
                path: '/chat',
                query: {
                  chat: chat
                }
              });
              // this.chatList.unshift(chat)
              // this.switchInterface('chat')  // 切换到聊天界面
              // this.changeChat(chat)    // 将当前聊天对象切换成该聊天
            }
          })
        }
      },
    },
    mounted () {
      this.openConnect();
      this.handleFriendList()
      this.$store.commit('setPage', 2);//设置需要预请求的参数
    },
    
  }

</script>
<style >
.dot{
  position: absolute;
  top: 25px;
  right: 5px;
  background-color: #fa5555;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 10px;
  width: 10px;
  text-align: center;
  white-space: nowrap;
  border: 1px solid #fff;
}

</style>
